package com.sbl.bajw.common;

import java.io.InputStream;
import java.sql.Blob;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


public class DataTable 
{
	List<Object[]> dataTable = new ArrayList<Object[]>();
	
	HashMap<String, Integer> columnIndexInfo = new HashMap<String,Integer>();
	String[] columnNames = null;
	
	int columnCount = 0;
	
	public DataTable(ResultSet result) throws Exception
	{
		ResultSetMetaData metaData = result.getMetaData();
		columnCount = metaData.getColumnCount();
		columnNames = new String[columnCount];
		
		for(int i = 0 ; i < columnCount; i ++)
		{
			String columnName = metaData.getColumnName(i+1);
			columnIndexInfo.put(columnName.toLowerCase(), i);
			columnNames[i] = columnName.toLowerCase();
		}
		
		while(result.next())
		{
			Object[] row = new Object[columnCount];
			for(int i = 0 ; i < columnCount; i ++)
			{
				Object val = result.getObject(i + 1);
				if(val != null && val.getClass().getName().toUpperCase().indexOf("BLOB") != -1)
				{
					row[i] = blob2ByteArr((Blob)val);
				}
				else
				{
					row[i] = val;
				}
				
			}
			dataTable.add(row);
		}
	}
	
	protected byte[] blob2ByteArr(Blob blob) throws Exception {
	     
        byte[] b = null;
        try {
            if (blob != null) {
            	InputStream inputStream = blob.getBinaryStream();
            	int length = (int) blob.length();
            	b = new byte[length];
            	inputStream.read(b);
            }
        } catch (Exception e) {
            throw new Exception(e);
        }
 
        return b;
    }
	
	public int getColumnCount()
	{
		return columnCount;
	}
	
	public HashMap<String, Integer> getColumnInfo()
	{
		return columnIndexInfo;
	}
	
	public List<Object[]> getDataTable()
	{
		return dataTable;
	}
	
	public Object getValue(int rowIndex,int columnIndex)
	{
		if(getRecordCount()==0 || rowIndex > getRecordCount())
		{
			return null;
		}
		return dataTable.get(rowIndex)[columnIndex];
	}
	
	public Object getValue(int rowIndex,String columnName)
	{
		if(!columnIndexInfo.containsKey(columnName.toLowerCase()))
		{
			return null;
		}
		
		int columnIndex = columnIndexInfo.get(columnName.toLowerCase());
		Object value = getValue(rowIndex,columnIndex);
		return value;
	}
	
	public String getString(int rowIndex,String columnName)
	{
		if(columnIndexInfo.get(columnName.toLowerCase()) == null){
			return null;
		}
		int columnIndex = columnIndexInfo.get(columnName.toLowerCase());
		Object value = getValue(rowIndex,columnIndex);
		
		if(value instanceof java.sql.Timestamp)
		{
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			Date date = new Date(((java.sql.Timestamp)value).getTime());
			return df.format(date);
		}
		
		if(value == null)
		{
			return "";
		}

		return (value+"").trim();
	}
	
	public String getString(int rowIndex,int columnIndex)
	{
		Object value = getValue(rowIndex,columnIndex);
		
		if(value instanceof java.sql.Timestamp)
		{
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			Date date = new Date(((java.sql.Timestamp)value).getTime());
			return df.format(date);
		}
		
		if(value == null)
		{
			return "";
		}

		return (value+"").trim();
	}
	
	public int getInt(int rowIndex,String columnName)
	{
		int columnIndex = columnIndexInfo.get(columnName.toLowerCase());
		Object value = getValue(rowIndex,columnIndex);
		return (Integer)value;
	}
	
	public Date getDate(int rowIndex,String columnName)
	{
		int columnIndex = columnIndexInfo.get(columnName.toLowerCase());
		Object value = getValue(rowIndex,columnIndex);
		return (Date)value;
	}
	
	public Timestamp getTimestamp(int rowIndex,String columnName)
	{
		int columnIndex = columnIndexInfo.get(columnName.toLowerCase());
		Object value = getValue(rowIndex,columnIndex);
		
		if(value instanceof Timestamp)
		{
			Timestamp time = (Timestamp)value;
			return time;
		}
		else if(value instanceof java.sql.Date)
		{
			java.sql.Date date = (java.sql.Date)value;
			Timestamp time = new Timestamp(date.getTime());
			return time;
		}
		else if(value instanceof Date)
		{
			Date date = (Date)value;
			Timestamp time = new Timestamp(date.getTime());
			return time;
		}
		else{
			return null;
		}
	}
	
	public Double getDouble(int rowIndex,String columnName)
	{
		int columnIndex = columnIndexInfo.get(columnName.toLowerCase());
		Object value = getValue(rowIndex,columnIndex);
		double result = 0;
		
		try {
			result = (Double)value;
			return result;
		} 
		catch (Exception e) {
			return null;
		}
	}
	
	public void setValue(int rowIndex,String columnName,Object value)
	{
		int columnIndex = columnIndexInfo.get(columnName.toLowerCase());
		dataTable.get(rowIndex)[columnIndex] = value;
	}
	
	public void setValue(int rowIndex,int columnIndex,Object value)
	{
		dataTable.get(rowIndex)[columnIndex] = value;
	}
	
	public int getRecordCount()
	{
		if(dataTable == null)
		{
			return 0;
		}
		else
		{
			return dataTable.size();
		}
	}
	
	public List<String> toStringList(String columnName){
		List<String> list = new ArrayList<String>();
		
		for(int i = 0 ; i < dataTable.size(); i++){
			String value = getString(i, columnName);
			list.add(value);
		}
		
		return list;
	}
	
	public String getColumnName(int columnIndex)
	{
		if(columnIndex >= columnNames.length)
		{
			return null;
		}
		String name = columnNames[columnIndex];
		return name;
	}
	
	public String toGridJosn(int pageSize,int pageCount,int pageIndex,int recordCount)
	{
		String json = toJson();
		String result = "{";
		result += "\"pageCount\":" +  "\""+pageCount+"\",";
		result += "\"pageIndex\":" +  "\""+pageIndex+"\",";
		result += "\"pageSize\":" +  "\""+pageSize+"\",";
		result += "\"RecordCount\":" +  "\""+recordCount+"\",";
		result += "\"GridData\":" +  json+"}";
		return result;
	}
	
	public String toJson()
	{
		StringBuilder resultBuilder = new StringBuilder("[");
		
		for (int j = 0;j<dataTable.size();j++) 
		{
			resultBuilder.append("{");
			for(int i = 0;i < columnCount ; i++)
			{
				String columnName = columnNames[i];
				resultBuilder.append("\""+columnName+"\":");
				resultBuilder.append("\""+dealWithJsonStr(getString(j, columnName))+"\"");
				int ccc = columnCount - 1;
				if(i < ccc)
				{
					resultBuilder.append(",");
				}
			}
			
			resultBuilder.append("}");
			
			if(j < (dataTable.size()-1))
			{
				resultBuilder.append(",");
			}
			
		}
		
		resultBuilder.append("]");
		return resultBuilder.toString();
	}
	
	private String dealWithJsonStr(String value)
	{
		if(value == null)
		{
			return null;
		}
		value = value.replaceAll("\\\\", "\\\\");
		value = value.replaceAll("\"", "\\\\\\\"");
		
		return value;
	}
	
}
